import sys
import time
import subprocess
from multiprocessing import Pool, RLock

# if len(sys.argv) != 3:
#     sys.exit(f"python {sys.argv[0]} work.sh cpu\n")


def runSH(sh):
    sp = subprocess.run(sh, shell=True, stderr=subprocess.PIPE)
    t = time.localtime()
    # submit date time
    # subDT = f'{t.tm_year}-{t.tm_mon:02}-{t.tm_mday:02} {t.tm_hour:02}:{t.tm_min:02}:{t.tm_sec:02}'
    # 
    lock.acquire()
    with open(worksh+f'.{dt}.plog', 'a') as runOut:
        # 若返回状态码为0 即任务执行成功
        if sp.returncode == 0:
            runOut.write(f'{subDT} Successed -> {sh}\n')
        else:
            runOut.write(f'{subDT} Failed    -> {sh}\n')
    # 
    lock.release()


# 返回一个保存不同时间格式元祖
def ftime():
    t = time.localtime()
    # ('20220614095527', '2022-06-14 09:55:27')
    return (f'{t.tm_year}{t.tm_mon:02}{t.tm_mday:02}{t.tm_hour:02}{t.tm_min:02}{t.tm_sec:02}', f'{t.tm_year}-{t.tm_mon:02}-{t.tm_mday:02} {t.tm_hour:02}:{t.tm_min:02}:{t.tm_sec:02}')


def init(l):
    global lock
    lock = l


if __name__ == '__main__':
    worksh = sys.argv[1]
    t = ftime()
    dt = t[0]
    # 20220614095527.plog
    with open(worksh+f'.{dt}.plog', 'w') as runOut:
        # === START 2022-06-14 09:55:27 START ===
        runOut.write(f'=== START {t[1]} START ===\n')
    # m = hashlib.md5(str(time.time()).encode('utf-8'))

    #
    lock = RLock()
    # 开启线程池
    p = Pool(int(sys.argv[2]), initializer=init, initargs=(lock,))

    # 将脚本跳过注释和空行 以行为单位开设子线程运行
    with open(worksh) as sh:
        for i in sh:
            i = i.strip()
            if not i or i.startswith('#'):
                continue
            # 单次启动一个任务，但是异步执行，启动后不等这个进程结束又开始执行新任务
            p.apply_async(runSH, (i, ))
    # 关闭线程池 不会有新的进程加入到pool中
    p.close()
    # 等待所有子进程结束
    p.join()

    # 生成plog日志文件
    with open(worksh+f'.{dt}.plog', 'a') as runOut:
        t = ftime()
        runOut.write(f'=== END   {t[1]}   END ===\n')
